package com.ruoyi.api.resolver;

import com.ruoyi.api.annotation.CurrentUser;
import com.ruoyi.system.domain.HyUser;
import com.ruoyi.system.service.IHyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户   解析器
 * @author lixin
 * @date 2021-07-01 16:15
 */
public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Autowired
	private IHyUserService apiUserService;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(HyUser.class) && parameter.hasParameterAnnotation(CurrentUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
								  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
		//获取用户ID
		Object object = request.getAttribute("userId", RequestAttributes.SCOPE_REQUEST);
		if (object == null) {
			return null;
		}

		//获取用户信息
		HyUser hyUser = apiUserService.getById((Long) object);


		return hyUser;

	}
}
